<?php
class HomeModule
{
	function index() {
		global $_G;
		$_GET['f'] = '';
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		
		//统计
		$stat['points'] = $_G['db']->result("SELECT point1 FROM ".table('user_stat')."WHERE uid='".$_G['uid']."'");
		$stat['points_order'] = $_G['db']->result("SELECT COUNT(1) FROM ".table('orders')."WHERE type='buypoint' AND status<3 AND uid='".$_G['uid']."'");
		
		$stat['msg'] = $_G['db']->result("SELECT COUNT(1) FROM".table('messages')."WHERE recvuid='".$_G['uid']."'") ;
		$stat['msg_new'] = $_G['db']->result("SELECT COUNT(1) FROM".table('messages')."WHERE new=1 AND recvuid='".$_G['uid']."'") ;
		
		//$stat['url'] = $_G['db']->result("SELECT COUNT(1) FROM".table('link')."WHERE uid='".$_G['uid']."'") ;
		//$stat['friend'] = $_G['db']->result("SELECT COUNT(1) FROM".table('friend')."WHERE uid='".$_G['uid']."'") ;
		//$stat['article'] = $_G['db']->result("SELECT COUNT(1) FROM".table('article')."WHERE uid='".$_G['uid']."'") ;
		
		//加载弹出框架
		loadialog();
		
		include template('uc/home');
	}
	function profile() {
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		switch($action) {
			case 'save':
				if(!IS_POST) {
					goto_page(url('home.php?f=profile'));
				}
				$result = array(
					'sex' => getGP('sex','P','int'),
					'birthday' => getGP('bornyear','P').'-'.str_pad(getGP('bornmonth','P'),2,'0',STR_PAD_LEFT).'-'.str_pad(getGP('bornday','P'),2,'0',STR_PAD_LEFT),
					'qq' => getGP('qq','P'),
					'phone' => getGP('phone','P'),
					'tel' => getGP('tel','P'),
					'msn' => getGP('msn','P'),
					'signature' => getGP('signature','P'),
				) ;
				if(isset($_FILES['avatar']) && $_FILES['avatar']['size']>1) {
					include libfile('upload.php');
					$upload = new upload($_G['settings']['upload']['allow_type'], $_G['settings']['upload']['file_size'], 'avatar');
					$upload->set_dir(BASE_ROOT.DATA_DIR.'avatar/');
					//对图像进行缩放
					$upload->set_resize(110, 135);
					$files = $upload->execute_single('u'.$_G['uid']);
					if($files['status'] == 1){
						$result['picture'] = $files['path'].$files['name'];
					}
				}
				$_G['db']->update('users',$result,array('uid'=>$_G['uid']));
				msg(Lang::get('prifile_saved'));
				break;
			case 'password':
				$reset = false;
				if(getGP('resetpass','c')) {
					$reset = true;
				}
				if(IS_POST) {
					$result = array(
						'oldpassword' => getGP('oldpassword','P'),
						'password' => getGP('password','P'),
						'repassword' => getGP('repassword','P'),
					) ;
					if($result['password'] != $result['repassword']) {
						msg(Lang::get('needed_repassword','user'));
					}
					if(!$reset && password($result['oldpassword'],$_G['users']['authkey'])!= $_G['users']['password']) {
						msg(Lang::get('oldpassword_wrong','user'));
					}
					$_G['userobj']->user_save(array('uid'=>$_G['uid']),array('password'=>trim($result['password']))) ;
					if($reset)set_cookie('resetpass', '');
					$password = $_G['db']->result("SELECT password FROM".table('users')."WHERE uid='".$_G['uid']."'");
					$auth = authcode("$_G[uid]\t".md5($password));
					set_cookie('auth', $auth, 86400 * 30);
					msg(Lang::get('chane_passwd_login','user'));
				}
				break;
			default:
				$result = $_G['users'];
		}
		include template('uc/profile');
	}
	
	function dianpin(){
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		$id = getGP('id','G','int');
		if(!$id)msg('参数错误');
		
		switch($action) {
			case 'save':
				vd($_POST);
				$pid=getGP('caidan','P','int');
				$star=getGP('star','P','int');
				$content=getGP('content','P','int');
				//条件判断
				if(!$pid || !$star || !$content){
					msg('请填写必要有选项');
				}
				/*
				 *   `cid` int(10) unsigned NOT NULL auto_increment,
  `referid` int(10) unsigned NOT NULL default '0',
  `shopid` int(10) unsigned NOT NULL default '0',
  `uid` int(10) unsigned NOT NULL default '0',
  `pid` int(10) unsigned NOT NULL default '0',
  `type` tinyint(1) NOT NULL default '0',
  `username` varchar(32) NOT NULL default '',
  `email` varchar(50) NOT NULL default '',
  `content` text NOT NULL,
  `dateline` int(10) unsigned NOT NULL default '0',
  `ip` varchar(15) NOT NULL default '',
  `reply` text NOT NULL,
  `replytime` int(10) NOT NULL default '0',
  `status` tinyint(1) NOT NULL default '0',
  `stars` tinyint(1) unsigned NOT NULL default '0',
  `ishide` tinyint(1) unsigned NOT NULL default '0',
				 */
				$data = array(
					'shopid'=>'',
					'uid' => '',
					'pid' => '',
					'username' => '',
					'type' => '0',
					'content' => '',
					'stars' => '',
					
				);
				
				
				break;
			default:
				$query = $_G['db']->query('SELECT * FROM'.table('orders_product')."WHERE txnid='$id' AND comment=0");
				while($data = $_G['db']->fetch_array($query)){
					$caidans[] = $data;
				}
		}
		include template('uc/dianpin');
	}
	
	function food() {
		global $_G;
		if(!$_G['users']['shopid']){
			msg('拒绝访问');
		}
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		switch($action) {
			case 'cate':
				$links = array();
				loadialog();
				$datas = $_G['db']->fetch_all("SELECT cid,catename,total FROM".table('category')."WHERE uid='$_G[uid]' AND type=2 " );
				break;
			case 'save':
				if(!IS_POST) {
					msg('禁止操作',('home.php?f=food'));
				}
				$pid = getGP('pid','P','int');
				$result = array(
					'stock' => getGP('stock','P','int'),
					'uid'	=> $_G['uid'],
					'cid' => getGP('cid','P','int'),
					'status' => getGP('status','P','int'),
					'price' => getGP('price','P'),
					'special' => getGP('special','P') == 'on'?1:0,
					'detail' => getGP('detail','P'),
					'title' => getGP('title','P'),
					'shopid' => $_G['users']['shopid'],
				) ;
				if(isset($_FILES['image']) && $_FILES['image']['size']>1) {
					include libfile('upload.php');
					$upload = new upload($_G['settings']['upload']['allow_type'], $_G['settings']['upload']['file_size'], 'image');
					$upload->set_dir(BASE_ROOT.DATA_DIR.'files/');
					//对图像进行缩放
					$upload->set_resize(110, 135);
					$files = $upload->execute_single('u'.$_G['uid']);
					if($files['status'] == 1){
						$result['image'] = str_replace(DATA_DIR.'files/', '', $files['path'].$files['name']);
					}
				}
				if($pid>0){
					$_G['db']->update('caidan',$result,array('uid'=>$_G['uid'],'pid'=>$pid));
					msg('编辑成功',$_G['gourl']);
				}else{
					$result['addtime'] = TIMESTAMP;
					$_G['db']->insert('caidan',$result);
					msg('添加成功','home.php?f=food');
				}
				
				break;
			case 'del':
				$id = getGP('id','G','int');
				if($id){
					$_G['db']->query("DELETE FROM".table('caidan')."WHERE pid='".$id."' AND uid='".$_G['uid']."' AND shopid='".$_G['users']['shopid']."'");
				}
				msg('操作成功','home.php?f=food');
			case 'edit':
				$data = $_G['db']->fetch('caidan','*',array('pid'=>getGP('id','G','int')))	;
			case 'add':
				$categorys = $_G['db']->fetch_all("SELECT cid,catename FROM".table('category')."WHERE uid='$_G[uid]' AND type=2 " );
				break;
			case 'special':
				$where =' AND m.special=1';	
			default:
				$limit = 15;
				$links = array();
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$where .= '';
				if($id) {
					$where .= ' AND l.cid='.$id;
				}
				$sql = 'SELECT m.* FROM'.table('caidan').'m WHERE m.uid='.$_G['uid'].$where;
				$query = $_G['db']->page_query($sql,$limit);
				$num = $_G['db']->result('SELECT m.*,c.catename FROM'.table('caidan').'m LEFT JOIN'.table('category').'c ON m.cid=c.cid WHERE c.type=2 AND m.uid='.$_G['uid'].$where);
				while($data = $_G['db']->fetch_array($query)) {
					$datas[] = $data ;
				}
				$query = $_G['db']->query("SELECT cid,catename FROM".table('category')."WHERE uid='$_G[uid]' AND type=2 " );
				while($d = $_G['db']->fetch_array($query)){
					$categorys[$d['cid']]=$d;
				}
				$pager = pager($num,$limit);
				
				
				
		}
		
		include template('uc/food');
	}	

	function join() {
		global $_G;
		if($_G['uid'] < 1){
			msg('请先登录','login.php');
		}
		if($_G['users']['shopid'] > 0){
			$has = $_G['db']->result("SELECT status FROM".table('shops')."WHERE shopid='".$_G['users']['shopid']."'");
			if($has){header("Location: ".url('home.php'));exit;}
		}
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		$has = $_G['db']->result("SELECT shopid FROM".table('shops')."WHERE uid='".$_G['uid']."'");
		switch($action) {
			case 'save':
				if(!IS_POST) {
					goto_page(url('home.php?f=join'));
				}
				if($has){
					msg('你已经申请过了');
				}
				
				$result = array(
					'cid' => getGP('stype','P','int'),
					'uid' => $_G['uid'],
					'username' => getGP('username','P'),
					'shopname' => getGP('shopname','P'),
					'opentime' => getGP('opentime','P'),
					'closetime' => getGP('closetime','P'),
					'tel' => getGP('tel','P'),
					'minprice' => getGP('minprice','P'),
					'addr1' => getGP('addr1','P'),
					'addr2' => getGP('street1','P'),
				    'bus' => getGP('bus','P'),
					'description' => getGP('description','P'),
					'tedian' => getGP('tedian','P'),
					'chengnuo' => getGP('chengnuo','P'),
					'sat' => getGP('res1','P','int'),
					'sun' => getGP('res2','P','int'),
					'rid' => getGP('rid','P','int')
				) ;
				
				$udata = array(
					'qq' => getGP('qq','P'),
					'phone' => getGP('phone','P'),
					'tel' => getGP('tel','P'),
				);
				if(!$result['username']){
					error('请填写店主姓名');
				}
				if(!$result['shopname']){
					error('请填写餐厅名称');
				}
				if(!$result['tel']){
					error('请填写订餐电话');
				}
				if(!$result['addr1']){
					error('请填写餐厅地址');
				}
				if(!$udata['phone'] && !$udata['tel'] ){
					error('请填写店主手机或	店主电话');
				}
					$shopid=$_G['db']->insert('shops',$result);
					$udata['shopid'] = $shopid;
					$_G['db']->update('users',$udata,array('uid'=>$_G['uid']));
				
				goto_page(url('home.php?f=join'));
				break;
			default:
				$result = $_G['db']->fetch('shops','*',array('shopid'=>$_G['users']['shopid']));
				m('uc/addr');
				$region=AddrModule::getaddr();
				$cates = $_G['cache']->get('category');
				$worktime1 = array('05:00','05:30','06:00','06:30','07:00','07:30','08:00','08:30','09:00','09:30','10:00','10:30','11:00','11:30');
				$worktime2 = array('12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30','16:00','16:30','17:00','17:30','18:00','18:30','19:00','19:30','20:00','20:30','21:00','21:30','22:00','22:30','23:00','23:30');
		
		
		}
		include template('join');
		
	}
	function sprofile() {
		global $_G;
		if(!$_G['users']['shopid']){
			msg('拒绝访问');
		}
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		switch($action) {
			case 'save':
				if(!IS_POST) {
					goto_page(url('home.php?f=sprofile'));
				}
				$result = array(
					'cid' => getGP('stype','P','int'),
					'uid' => $_G['uid'],
					'shopname' => getGP('shopname','P'),
					'opentime' => getGP('opentime','P'),
					'closetime' => getGP('closetime','P'),
					'tel' => getGP('tel','P'),
					'minprice' => getGP('minprice','P'),
					'minnum' => getGP('minnum','P','int')>0?getGP('minnum','P','int'):1,
					'extprice' => getGP('extprice','P'),
					'addr1' => getGP('addr1','P'),
					'addr2' => getGP('street1','P'),
					'bus' => getGP('bus','P'),
					'tedian' => getGP('tedian','P'),
					'chengnuo' => getGP('chengnuo','P'),
					'description' => getGP('description','P'),
					'sat' => getGP('res1','P','int'),
					'sun' => getGP('res2','P','int'),
					'rid' => getGP('rid','P','int'),
				) ;
				if(isset($_FILES['avatar']) && $_FILES['avatar']['size']>1) {
					include libfile('upload.php');
					$upload = new upload($_G['settings']['upload']['allow_type'], $_G['settings']['upload']['file_size'], 'avatar');
					$upload->set_dir(BASE_ROOT.DATA_DIR.'avatar/');
					//对图像进行缩放
					$upload->set_resize(120, 100);
					$files = $upload->execute_single('s'.$_G['uid']);
					if($files['status'] == 1){
						$result['logo'] = str_replace(DATA_DIR, '',$files['path'].$files['name']);
					}
				}
				if(!$_G['store']['shopid']) {
					$shopid=$_G['db']->insert('shops',$result);
					$_G['db']->update('users',array('shopid'=>$shopid),array('uid'=>$_G['uid']));
				}else{
					$_G['db']->update('shops',$result,array('uid'=>$_G['uid'],'shopid'=>$_G['store']['shopid']));
				}
				msg('资料修改成功','home.php?f=sprofile');
				break;
			case 'password':
				$reset = false;
				if(getGP('resetpass','c')) {
					$reset = true;
				}
				if(IS_POST) {
					$result = array(
						'oldpassword' => getGP('oldpassword','P'),
						'password' => getGP('password','P'),
						'repassword' => getGP('repassword','P'),
					) ;
					if($result['password'] != $result['repassword']) {
						msg(Lang::get('needed_repassword','user'));
					}
					if(!$reset && password($result['oldpassword'],$_G['users']['authkey'])!= $_G['users']['password']) {
						msg(Lang::get('oldpassword_wrong','user'));
					}
					$_G['userobj']->user_save(array('uid'=>$_G['uid']),array('password'=>trim($result['password']))) ;
					if($reset)set_cookie('resetpass', '');
					$password = $_G['db']->result("SELECT password FROM".table('users')."WHERE uid='".$_G['uid']."'");
					$auth = authcode("$_G[uid]\t".md5($password));
					set_cookie('auth', $auth, 86400 * 30);
					msg(Lang::get('chane_passwd_login','user'));
				}
				break;
			default:
				$result = $_G['db']->fetch('shops','*',array('shopid'=>$_G['users']['shopid']));
				m('addr');
				$region=AddrModule::getaddr($result['rid']);	
				$cates = $_G['cache']->get('category');
				$worktime1 = array('05:00','05:30','06:00','06:30','07:00','07:30','08:00','08:30','09:00','09:30','10:00','10:30','11:00','11:30');
				$worktime2 = array('12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30','16:00','16:30','17:00','17:30','18:00','18:30','19:00','19:30','20:00','20:30','21:00','21:30','22:00','22:30','23:00','23:30');
		
		
		}
		include template('uc/sprofile');
	}
	function category(){
		/*
		 * 类别权限状态status
		 * 0 默认 全站开放
		 * 1 好友可见
		 * 2 自己可见
		 * 
		 */
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		switch($action) {
			case 'edit':
				$cates['catename'] = getGP('name','G');
				$cates['total'] = getGP('total','G','int');
				$id = getGP('id','G','int');
				$_G['db']->update('category',$cates,array('cid'=>$id,'uid'=>$_G['uid']));
				$cates['mstatus'] = true;
				
				print_R(json_encode($cates));
				exit;	
				break;
			case 'del':
				$id = getGP('id','G','int');
				$_G['db']->query("DELETE FROM".table('category')."WHERE cid='".$id."' AND uid='".$_G['uid']."'");
				if($_G['db']->affected_rows()){
					$data['status'] = true;
				}else{
					$data['status'] = false;
					$data['msg'] = $lang['no_access'];
				}
				print_R(json_encode($data));
				exit;
				break;
			case 'save':
				if($_G['uid']<1){
					exit('0');
				}
				
				$cates['uid'] = $_G['uid'];
				$cates['catename'] = getGP('name','G');
				$cates['status'] = getGP('cstatus','G','int');
				$cates['cid'] = getGP('id','G','int');
				$cates['type'] = 2;
				
				if($cates['cid']<1){
					$exist = $_G['db']->result("SELECT cid FROM ".table('category')." WHERE (uid='".$cates['uid']."' OR uid=0) AND catename='".$cates['catename']."'");
					
					if($exist){
						$cates['mstatus'] = false;
						$cates['msg'] = $lang['category_exists'];
						
					}else{
						$cates['cid'] = $_G['db']->insert("category",$cates);
						if($cates['cid']){
							$cates['mstatus'] = true;
						}
					}
				}else{
					$exist = $_G['db']->result("SELECT cid FROM ".table('category')." WHERE (uid='".$cates['uid']."' OR uid=0) AND catename='".$cates['catename']."' AND cid!='".$cates['cid']."'");
					if($exist){
						$cates['mstatus'] = false;
						$cates['msg'] = $lang['category_exists'];
						
					}else{
						$_G['db']->update("category",$cates,array('cid'=>$cates['cid'],'uid'=>$_G['uid'] ));
						$cates['mstatus'] = true;
					}
				}
				if(!$cates['mstatus'])$cates['mstatus'] = false;
				
				print_R(json_encode($cates));
				exit;
				breaK;
			default:
				$type =getGP('t','G','int');
				$limit = 13;
				loadialog();
				$categorys = array();
				$t = getGP('t','G','int');
				$where = " AND type='".$t."'";
				$sql = 'SELECT * FROM '.table('category').'WHERE uid='.$_G['uid'].$where." ORDER BY cid DESC ";
				$query = $_G['db']->page_query($sql,$limit);
				$num = $_G['db']->result('SELECT count(cid) as num FROM'.table('category').'WHERE uid='.$_G['uid'].$where);
				while($data = $_G['db']->fetch_array($query)) {
					$categorys[] = $data ;
				}
				$category_access = array(
					'0'	=> $lang['open_all'],
					'1'	=> $lang['only_myfriend'],
					'2'	=> $lang['only_myself'],
				);
				$pager = pager($num,$limit);
				
				
				switch($type){
					case '0'://文章、日记分类
						include template('article');
				}
				
		}
				
	}
	function article() {
		/*
		 * 文章权限状态status
		 * 1 默认 全站开放
		 * 4 草稿
		 * 3 自己可见
		 * 2 锁定
		 * 5 好友可见
		 * 0 继承类别权限
		 */
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		switch($action) {
			case 'del':
				if(!$_G['uid'])return;
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$result = $_G['db']->fetch('article','cid',array('aid'=>$id,'uid'=>$_G['uid']));
				if($result['cid']) {
					$_G['db']->update("article",array('isdraft'=>1),array('aid'=>$id));
					//$_G['db']->query("DELETE FROM ".DB_PREFIX."article WHERE aid=".$id);
					//$_G['db']->query("UPDATE ".DB_PREFIX."category SET total=total-1 WHERE type=0 AND cid=".$result['cid']);
					//recache('category');
					//$_G['cache']->del($id,'article');
					$data['status'] = true;
				}else{
					$data['status'] = false;
					$data['msg'] = $lang['no_access'];
				}
				if($_GET['ajax']){
					print_R(json_encode($data));
					exit;
				}else{
					goto_page(url('home.php?f=article'));
				}
				break;
			case 'edit':
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$article = $_G['db']->fetch('article','*',array('aid'=>$id,'uid'=>$_G['uid']));
				$categorys = $_G['db']->fetch_all("SELECT catename ,cid FROM".table('category')."WHERE uid=0 OR uid='".$_G['uid']."'");
				
				$attachments = $_G['db']->fetch_all("SELECT fid,originalname,filepath,thumb,filesize,filetype,fileext,dateline FROM ".DB_PREFIX."files WHERE referid = '$id' AND type = 0");
				
				break;
			case 'add':	
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$article = $_G['db']->fetch('article','*',array('aid'=>$id,'uid'=>$_G['uid']));
				$categorys = $_G['db']->fetch_all("SELECT catename ,cid FROM".table('category')."WHERE uid=0 OR uid='".$_G['uid']."'");
				//loadialog();
				break;
			case 'save':
				$article['aid'] = getGP('aid','P','int');
				$article['status'] = getGP('status','P','int');
				$article['cid'] = getGP('cid','P','int');
				$article['title'] = getGP('title','P');
				$article['content'] = getGP('content','P');
				$article['summary'] = getGP('summary','P');
				$todraft = getGP('todraft','P','int');
				if($todraft){//only owner can see draft
					$article['isdraft'] = 1;
				}
				if(!$article['aid']) {//new
					$article['uid'] = $_G['uid'];
					$article['username'] = $_G['username'];
				}
				if (empty($article['title']))
					$errmsg[] = '请填写文章标题。';
				if (!$article['cid'])
					$errmsg[] = '请选择日志类别。';
				if (count($errmsg)) {
					error($errmsg);
				}
				if (!$article['aid']) {//new
					if (  !ISADMIN && !ican('post_article') ) {
						error('对不起，你没有发表文章的权限！');
					} else {
						$article['uid'] = $_G['uid'];
						$article['username'] = $_G['username'];
						$article['dateline'] = TIMESTAMP;
						if ($aid = $_G['db']->insert('article',$article)) {
							$article['aid'] = $aid;
						}
					}
				} else {
					if ( !($uid = $_G['db']->result("SELECT uid FROM ".DB_PREFIX."article WHERE aid = '$article[aid]' AND uid='$_G[uid]'")) ) {
						error('文章不存在或已删除。');
					} else {
						if ( !ISADMIN ) {
							if ( !ican('edit_all_article') ) {
								if ( !ican('edit_article') ) {
									error('对不起，你没有编辑文章的权限。');
								} elseif ( $uid != $_G['uid'] ) {
									error('对不起，你没有编辑他人文章的权限。');
								}
							}
						}
						$_G['db']->update('article', $article, array('aid' => $article['aid']));
					}
					$_G['cache']->del($article['aid'],'article') ;
				}
				//检查文章附件
				$attachments = getGP('user_upload_attachments'.$_G['uid'],'c');
				if ( !empty($attachments) && preg_match('/^([0-9]+(,[0-9])?)+$/', $attachments) ) {
					$_G['db']->query("UPDATE ".DB_PREFIX."files SET referid = $article[aid] WHERE fid IN ($attachments)");
					set_cookie('user_upload_attachments'.$_G['uid']);
				}
				recache('archive,lastest_article');
				goto_page(url('home.php?f=article'));
				break;
			case 'cates':
					$this->category();
					exit;
				break;
			case 'update':
				$id = getGP('id','G','int');
				$_G['db']->update("article",array('isdraft' => 0),array('aid'=>$id,'uid'=>$_G['uid']));
				if($_G['db']->affected_rows()){
					$data['status'] = true;
				}else{
					$data['status'] = false;
					$data['msg'] = $lang['update_article_error'];
				}
				print_R(json_encode($data));
				exit;
				break;	
			case 'draft': 
				$draft = true;
			default:
				$limit = 15;
				$articles = array();
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$t = getGP('t','G','int');
				$where = '';
				if($id) {
					$where = ' AND l.cid='.$id;
				}
				if($t){
					$where .=" AND a.status='".$t."'";
				}
				if($draft){
					$where .=" AND a.isdraft>0";
				}else{
					$where .=" AND a.isdraft=0";
				}
				$sql = 'SELECT a.*,c.catename,c.status as permission FROM '.table('article').'a LEFT JOIN '.table('category').'c ON a.cid=c.cid WHERE a.uid='.$_G['uid'].$where." ORDER BY a.aid DESC ";
				$query = $_G['db']->page_query($sql,$limit);
				$num = $_G['db']->result('SELECT count(a.aid) as num FROM'.table('article').'a LEFT JOIN'.table('category').'c ON a.cid=c.cid WHERE a.uid='.$_G['uid'].$where);
				while($data = $_G['db']->fetch_array($query)) {
					$articles[] = $data ;
				}
				$article_access = array(
					'1'	=> $lang['open_all'],
					'3'	=> $lang['only_myself'],
					'5'	=> $lang['only_myfriend'],
					'4'	=> $lang['draft'],
					'2'	=> $lang['lock']
				);
				$category_access = array(
					'0'	=> $lang['open_all'],
					'1'	=> $lang['only_myfriend'],
					'2'	=> $lang['only_myself'],
				);
				$pager = pager($num,$limit);
				
		}
		include template('article');
	}
	function notice() {
		global $_G;
		if(!$_G['users']['shopid']){
			msg('拒绝访问');
		}
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		switch($action) {
			case 'del':
				if(!$_G['uid'])return;
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$result = $_G['db']->fetch('notice','aid',array('aid'=>$id,'uid'=>$_G['uid']));
				if($result['aid']) {
					$_G['db']->update("notice",array('isdraft'=>1),array('aid'=>$id));
					//$_G['db']->query("DELETE FROM ".DB_PREFIX."notice WHERE aid=".$id);
					//$_G['db']->query("UPDATE ".DB_PREFIX."category SET total=total-1 WHERE type=0 AND cid=".$result['cid']);
					//recache('category');
					//$_G['cache']->del($id,'notice');
					$data['status'] = true;
				}else{
					$data['status'] = false;
					$data['msg'] = $lang['no_access'];
				}
				if($_GET['ajax']){
					print_R(json_encode($data));
					exit;
				}else{
					msg('删除成功','home.php?f=notice');
				}
				break;
			case 'edit':
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$article = $_G['db']->fetch('notice','*',array('aid'=>$id,'uid'=>$_G['uid']));
				$categorys = $_G['db']->fetch_all("SELECT catename ,cid FROM".table('category')."WHERE uid=0 OR uid='".$_G['uid']."'");
				
				$attachments = $_G['db']->fetch_all("SELECT fid,originalname,filepath,thumb,filesize,filetype,fileext,dateline FROM ".DB_PREFIX."files WHERE referid = '$id' AND type = 0");
				
				break;
			case 'add':	
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$article = $_G['db']->fetch('notice','*',array('aid'=>$id,'uid'=>$_G['uid']));
				$categorys = $_G['db']->fetch_all("SELECT catename ,cid FROM".table('category')."WHERE uid=0 OR uid='".$_G['uid']."'");
				//loadialog();
				break;
			case 'save':
				$article['aid'] = getGP('aid','P','int');
				$article['status'] = getGP('status','P','int');
				$article['cid'] = getGP('cid','P','int');
				$article['title'] = getGP('title','P');
				$article['content'] = getGP('content','P');
				$article['summary'] = getGP('summary','P');
				$todraft = getGP('todraft','P','int');
				if($todraft){//only owner can see draft
					$article['isdraft'] = 1;
				}else{
					$article['isdraft'] = 0;
				}
				if(!$article['aid']) {//new
					$article['uid'] = $_G['uid'];
					$article['username'] = $_G['username'];
				}
				if (empty($article['title'])){
					msg('请填写文章标题。');
				}
				if (!$article['aid']) {//new
					if (  !ISADMIN && !ican('post_article') ) {
						msg('对不起，你没有发表文章的权限！');
					} else {
						$article['uid'] = $_G['uid'];
						$article['username'] = $_G['username'];
						$article['dateline'] = TIMESTAMP;
						if ($aid = $_G['db']->insert('notice',$article)) {
							$article['aid'] = $aid;
						}
					}
				} else {
					if ( !($uid = $_G['db']->result("SELECT uid FROM ".DB_PREFIX."notice WHERE aid = '$article[aid]' AND uid='$_G[uid]'")) ) {
						msg('文章不存在或已删除。');
					} else {
						if ( !ISADMIN ) {
							if ( !ican('edit_all_article') ) {
								if ( !ican('edit_article') ) {
									msg('对不起，你没有编辑文章的权限。');
								} elseif ( $uid != $_G['uid'] ) {
									msg('对不起，你没有编辑他人文章的权限。');
								}
							}
						}
						$_G['db']->update('notice', $article, array('aid' => $article['aid']));
					}
					$_G['cache']->del($article['aid'],'notice') ;
				}
				//检查文章附件
				$attachments = getGP('user_upload_attachments'.$_G['uid'],'c');
				if ( !empty($attachments) && preg_match('/^([0-9]+(,[0-9])?)+$/', $attachments) ) {
					$_G['db']->query("UPDATE ".DB_PREFIX."files SET referid = $article[aid] WHERE fid IN ($attachments)");
					set_cookie('user_upload_attachments'.$_G['uid']);
				}
				msg('操作成功','home.php?f=notice');
				break;
			case 'cates':
					$this->category();
					exit;
				break;
			case 'update':
				$id = getGP('id','G','int');
				$_G['db']->update("notice",array('isdraft' => 0),array('aid'=>$id,'uid'=>$_G['uid']));
				if($_G['db']->affected_rows()){
					$data['status'] = true;
				}else{
					$data['status'] = false;
					$data['msg'] = $lang['update_article_error'];
				}
				print_R(json_encode($data));
				exit;
				break;	
			case 'draft': 
				$draft = true;
			default:
				$limit = 15;
				$articles = array();
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$t = getGP('t','G','int');
				$where = '';
				if($id) {
					$where = ' AND l.cid='.$id;
				}
				if($t){
					$where .=" AND a.status='".$t."'";
				}
				if($draft){
					$where .=" AND a.isdraft>0";
				}else{
					$where .=" AND a.isdraft=0";
				}
				$sql = 'SELECT a.*,c.catename,c.status as permission FROM '.table('notice').'a LEFT JOIN '.table('category').'c ON a.cid=c.cid WHERE a.uid='.$_G['uid'].$where." ORDER BY a.aid DESC ";
				$query = $_G['db']->page_query($sql,$limit);
				$num = $_G['db']->result('SELECT count(a.aid) as num FROM'.table('notice').'a LEFT JOIN'.table('category').'c ON a.cid=c.cid WHERE a.uid='.$_G['uid'].$where);
				while($data = $_G['db']->fetch_array($query)) {
					$articles[] = $data ;
				}
				$article_access = array(
					'1'	=> $lang['open_all'],
					'3'	=> $lang['only_myself'],
					'5'	=> $lang['only_myfriend'],
					'4'	=> $lang['draft'],
					'2'	=> $lang['lock']
				);
				$category_access = array(
					'0'	=> $lang['open_all'],
					'1'	=> $lang['only_myfriend'],
					'2'	=> $lang['only_myself'],
				);
				$pager = pager($num,$limit);
				
		}
		include template('uc/notice');
	}
	function message(){
		global $_G;
		if(!$_G['users']['shopid']){
			msg('拒绝访问','home.php');
		}
		
		
	}
	function web() {
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		loadialog();
		switch($action) {
			case 'del':
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$result = $_G['db']->fetch('link','cid',array('lid'=>$id,'uid'=>$_G['uid']));
				if($result['cid']) {
					$_G['db']->query("DELETE FROM ".DB_PREFIX."link WHERE lid=".$id);
					$_G['db']->query("UPDATE ".DB_PREFIX."category SET total=total-1 WHERE cid=".$result['cid']);
					recache('link,category');
					$data['status'] = true;
				}else{
					$data['status'] = false;
					$data['msg'] = $lang['no_access'];
				}
				if($_GET['inajax']){
					print_R(json_encode($data));
					exit;
				}
				goto_page(url('home.php?f=web'));
				break;
			case 'edit':
			case 'add':	
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$result = $_G['db']->fetch('link','*',array('lid'=>$id,'uid'=>$_G['uid']));
				$linkgroup = $_G['cache']->get('linkgroup');
				break;
			case 'save':
				if(!IS_POST || !$_G['uid']) {
					goto_page(url('home.php?f=web'));
				}
				$savetype = getGP('savetype','P');
				$id = getGP('id','P','int');
				$link = array(
					'cid' => getGP('cid','P','int'),
					'title' => check_str(getGP('title','P')),
					'url' => check_str(getGP('url','P')),
					'rssurl' => check_str(getGP('rssurl','P')),
					'summary' => check_str(getGP('summary','P')),
					'visible' => getGP('visible','P','int')
				);
				if(!trim($link['title']) || !is_url($link['url']) || !$_G['uid']) {
					error(l('url_info_error','user'));
				}
				$link['uid'] = $_G['uid']; 
				if ($savetype == 'add') {
					$link['dateline'] = TIMESTAMP;
					if ($_G['db']->insert('link',$link)) {
						$_G['db']->query("UPDATE ".DB_PREFIX."category SET total=total+1 WHERE cid=".$link['cid']);
						recache('link,category');
						goto_page(url('home.php?f=web'));
					}
				} elseif ($savetype) {
					$_G['db']->update('link',$link, array('lid'=>$id));
					recache('link');
					goto_page(url('home.php?f=web'));
				}
				break;
			case 'all':
				$limit = 15;
				$links = array();
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$where = '';
				if($id) {
					$where = ' AND l.cid='.$id;
				}
				$sql = 'SELECT l.*,c.catename FROM '.DB_PREFIX.'link l LEFT JOIN '.DB_PREFIX.'category c ON l.cid=c.cid WHERE 1'.$where;
				$query = $_G['db']->page_query($sql,$limit);
				$num = $_G['db']->result('SELECT count(l.lid) as num FROM '.DB_PREFIX.'link l LEFT JOIN '.DB_PREFIX.'category c ON l.cid=c.cid WHERE 1 '.$where);
				while($data = $_G['db']->fetch_array($query)) {
					$links[] = $data ;
				}
				$pager = pager($num,$limit);
				break;
			default:
				$limit = 15;
				$links = array();
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$where = '';
				if($id) {
					$where = ' AND l.cid='.$id;
				}
				$sql = 'SELECT l.*,c.catename FROM '.DB_PREFIX.'link l LEFT JOIN '.DB_PREFIX.'category c ON l.cid=c.cid WHERE l.uid='.$_G['uid'].$where;
				$query = $_G['db']->page_query($sql,$limit);
				$num = $_G['db']->result('SELECT count(l.lid) as num FROM '.DB_PREFIX.'link l LEFT JOIN '.DB_PREFIX.'category c ON l.cid=c.cid WHERE l.uid='.$_G['uid'].$where);
				while($data = $_G['db']->fetch_array($query)) {
					$links[] = $data ;
				}
				$pager = pager($num,$limit);
		}
		include template('uc/home');
	}
	
	function msg(){
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		$group = array($lang['strange'],$lang['classmate'],$lang['colleague'],$lang['relative'],$lang['friend'],$lang['subordinate'],$lang['leader'],$lang['attention']);
		$msg_status = array($lang['readed'],$lang['no_read']);
		
		switch( $action ) {
			case 'del'://并不真正的删除消息，只标志为已删除
				$id = getGP('id','G','int');
				$_G['db']->query("UPDATE".table('messages')."SET delflag=1 WHERE pmid='".$id."' AND recvuid='".$_G['uid']."'");
				if($_G['db']->affected_rows()){
					$data['status'] = true;
				}
//				else{
//					$data['status'] = false;
//					$data['msg'] = $lang['no_access'];
//				}
				print_R(json_encode($data));
				exit;
				break;
			case 'add':
				msg($lang['no_access']);
				if(IS_POST){
					$recuids = array();
					if($_POST['receiver'] && $_POST['receiver'] !=$lang['input_friend_name']){
						$recuids[] = $_G['db']->result("SELECT uid FROM ".DB_PREFIX."users WHERE username='".$_POST['receiver']."'");
					}
					if(empty($_POST['friended']) && (empty($recuids) || !$recuids['0'] )){
						error($lang['needed_frined_name']);
					}
					if(strlen($_POST['extra']) <4 ){
						error($lang['needed_extra']);
					}
					if(!empty($_POST['friended'])){
						foreach($_POST['friended'] as $v){
							$recuids[] = substr($v,3);
						}
					}
					foreach ($recuids as $re){
						if($re && $re!=$_G['uid'])
						$sql .=$tag."('$_G[uid]','$re','$_POST[extra]','".TIMESTAMP."')";
						$tag = ',';
					}
					if($sql && $_G['db']->query("INSERT INTO ".DB_PREFIX."messages(senduid,recvuid,content,posttime) VALUES ".$sql)){
						msg($lang['send_msg_success'],"home.php?f=msg&a=outbox");
					}
				}
				break;
			case 'outbox':
				$limit = 15;
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$where = '';
				if($id) {
					$where = ' AND m.pmid='.$id;
				}
				$sql = 'SELECT m.*,u.username FROM'.table('messages').'m LEFT JOIN'.table('users').'u ON m.recvuid=u.uid WHERE m.senduid = '.$_G['uid'].$where;
				$query = $_G['db']->page_query($sql,$limit);
				$num = $_G['db']->result('SELECT count(1) FROM '.DB_PREFIX.'messages m  WHERE m.senduid = '.$_G['uid'].$where);
				while($data = $_G['db']->fetch_array($query)) {
					$msgs[] = $data ;
				}
				$pager = pager($num,$limit);
				break;
			case 'inbox':	
			default:
				$limit = 15;
				$id = isset($_GET['id'])?intval($_GET['id']):0;
				$where = '';
				if($id) {
					$where = ' AND m.pmid='.$id;
				}
				$sql = 'SELECT m.*,u.username FROM'.table('messages').'m LEFT JOIN'.table('users').'u ON m.senduid=u.uid WHERE m.delflag=0 AND m.recvuid = '.$_G['uid'].$where;
				$query = $_G['db']->page_query($sql,$limit);
				$num = $_G['db']->result('SELECT count(1) FROM '.DB_PREFIX.'messages m  WHERE m.delflag=0 AND m.recvuid = '.$_G['uid'].$where);
				while($data = $_G['db']->fetch_array($query)) {
					$msgs[] = $data ;
				}
				$pager = pager($num,$limit);
				break;
				
		}
		include template('uc/messages');
	}
	function friend(){
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('user');
		$sex = array($lang['woman'],$lang['man'],$lang['other']);
		loadialog();
		$group = array($lang['strange'],$lang['classmate'],$lang['colleague'],$lang['relative'],$lang['friend'],$lang['subordinate'],$lang['leader'],$lang['attention']);
		$wage = array('0-2000','2000-3000','3000-4000','4000-5000','5000-7000','7000-10000','10000-15000','15000-20000','>50000');
		$edu = array($lang['junior_school'],$lang['technical_school'],$lang['senior_school'],$lang['college'],$lang['undergraduate'],$lang['master'],$lang['doctor'],$lang['postdoctoral']);
		$blood = array($lang['type_a'],$lang['type_b'],$lang['type_ab'],$lang['type_o'],$lang['other']);
		$height = range(144,196);
		$weight = range(39,121);
		$_G['scripts'][]="static/script/calendar.js";

		switch( $action ) {
			case 'add':
				$data = array(
						'uid' => '',
						'name' => '',
						'born' => '',
						'sex' => '',
						'wage' => '',
						'mail' => '',
						'qq' => '',
						'tel' => '',
						'phone' => '',
						'status' => '',
						'gid' => '',
						'addr' => '',
						'addr1' => '',
						'picture' => '',
						'addtime' => '',
						'lasttime' => '',
						'hobby' => '',
						'extra' => '',
				) ;
				break;
			case 'edit':
				$fid = getGP('id','G','int');
				if(!$fid){
					exit($lang['invalid_request']);
				}
				$data = $_G['db']->fetch('friend','*',array('fid'=>$fid));
				$data['born'] =gdate('Y-m-d',$data['born']);
				$data['lasttime'] =gdate('Y-m-d',$data['lasttime']);
				$data['addtime'] =gdate('Y-m-d',$data['addtime']);
				break;
			case 'save':
				$fid = getGP('id','','int');
					$result = array(
						'uid' => $_G['uid'],
						'name' => getGP('name','P'),
						'born' => intval(gtime( getGP('birthday','P'))),
						'sex' => getGP('sex','P','int'),
						'marry'	=> getGP('marry','P','int'),
						'wage' => getGP('wage','P','int'),
						'blood' => getGP('blood','P','int'),
						'height' => getGP('height','P','int'),
						'weight' => getGP('weight','P','int'),
						'edu' => getGP('edu','P','int'),
						'mail' => getGP('mail','P'),
						'qq' => getGP('qq','P'),
						'tel' => getGP('tel','P'),
						'phone' => getGP('phone','P'),
						'status' => getGP('phone','P','int'),
						'gid' => getGP('gid','P','int'),
						'prov1' => getGP('prov1','P','int'),
						'prov2' => getGP('prov2','P','int'),
						'city1' => getGP('city1','P','int'),
						'city2' => getGP('city2','P','int'),
						'addr1' => getGP('addr1','P'),
						'addr2' => getGP('addr2','P'),
						'addtime' => intval(gtime( getGP('addtime','P'))),
						'lasttime' => intval(gtime( getGP('lasttime','P'))),
						'hobby' => getGP('hobby','P'),
						'extra' => getGP('extra','P'),
				) ;
				if(!$fid){
					$fid = $_G['db']->insert('friend',$result);
					$new = true;
					//goto_page(url('home.php?f=friend'));
				}else{
					$belong = $_G['db']->result("SELECT fid FROM ".DB_PREFIX."friend WHERE uid='{$_G['uid']}' AND fid='{$fid}'");
					if(!$belong)exit($lang['invalid_request']);
					$_G['db']->update('friend',$result,array('fid'=>$fid));
					$new = false;
				}
				if(isset($_FILES['avatar']) && $_FILES['avatar']['size']>1) {
					include libfile('upload.php');
					$upload = new upload($_G['settings']['upload']['allow_type'], $_G['settings']['upload']['file_size'], 'avatar');
					$upload->set_dir(BASE_ROOT.DATA_DIR.'avatar/');
					//对图像进行缩放
					$upload->set_resize(110, 135);
					$files = $upload->execute_single('f'.$fid);
					if($files['status'] == 1){
						$_G['db']->update('friend',array('avatar'=>$files['path'].$files['name']),array('fid'=>$fid));
					}
				}
				if($new){
					goto_page(url('home.php?f=friend'));
				}else{
					exit('<p align="center">'.$lang['change_success'].'</p><p align="center"><a href="'.url('home.php?f=friend&a=edit&ajax=1&id='.$fid).'">'.$lang['continue_edit'].'</a> <a href="javascript:;" onclick="window.parent.location.reload();">'.$lang['close'].'</a> </p>');
				}
				break;	
			case 'del':
				$fid = getGP('id','','int');
				$data['status'] = false;
				$data['msg'] = $lang['invalid_request'];
				
				$_G['db']->query("DELETE FROM ".DB_PREFIX."friend WHERE uid='{$_G['uid']}' AND fid='{$fid}'");
				if($_G['db']->affected_rows()){
					$data['status'] = true;
					$data['msg'] = $lang['del_success'];
				}
				print_R(json_encode($data));
				exit;
				break;
			case 'ajaxlist':
				$gid = getGP('id','','int');
				$data['status'] = false;
				$data['data']= array();
				
				if($gid<0){
					$where = '';
				}else{
					$where = " AND gid='".$gid."'";
				}
				$query = $_G['db']->query("SELECT fuid,name FROM ".DB_PREFIX."friend WHERE fuid>0 AND uid='{$_G['uid']}'".$where." LIMIT 40");
				
				while($result = $_G['db']->fetch_array($query)) {
					$data['data'][] = $result ;
				}
				if(!empty($data['data'])){
					$data['status'] = true;
				}
				print_R(json_encode($data));
				exit;
				
				break;
			case 'list':			
			default:
				$limit = 15;
				$links = array();
				if(isset($_GET['gid']))$where = " AND gid='".getGP('gid','G','int')."'";
				$field = getGP('search_field','P');
				if($field)$where .= " AND (name LIKE '%$field%' OR qq LIKE '%$field%' OR phone LIKE '%$field%')";
				$sql = 'SELECT * FROM '.DB_PREFIX.'friend WHERE uid='.$_G['uid'].$where;
				$query = $_G['db']->page_query($sql,$limit);
				$num = $_G['db']->result('SELECT count(1) as num FROM '.DB_PREFIX.'friend  WHERE uid='.$_G['uid'].$where);
				while($data = $_G['db']->fetch_array($query)) {
					$friends[] = $data ;
				}
				$pager = pager($num,$limit);
		}
		if(isset($_GET['ajax']) && isset($_GET['ajax'])) {
			include template('uc/friend_ajax');
		}else{
			include template('uc/friend');
		}
	}

	function album(){
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		$lang = lang::load('point');
		loadialog();
		switch ($action){
			case 'add':
			case 'edit':	
			break;
			case 'save':
			break;
			case 'del':
			break;		
			default:
			break;	
		}
		include template('uc/album');
	}
	function favo(){
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		loadialog();
		switch ($action){
			case 'shop':
			case 'caidan':	
			break;
			case 'save':
			break;
			case 'del':
			break;		
			default:
			break;	
		}
		include template('uc/favo');
	}
	function caipu(){
		global $_G;
		$action = isset($_GET['a'])?$_GET['a']:null;
		loadialog();
		switch ($action){
			case 'diary':
			break;
			case 'save':
			break;
			case 'del':
			break;
			case 'hobby':	
			break;		
			default:
			break;	
		}
		include template('uc/caipu');
	}
}	